const fs = require('fs')
const https = require('https')
const uri = require("./wechat/config")

function getWeChatUrlScheme() {
    return new Promise(async (reslove, reject) => {
        const data = await getWeChatAccessToken()
        const request = https.request(`https://api.weixin.qq.com/wxa/generatescheme?access_token=${data.access_token}`, {
            method: "POST",
            data: {
                access_token: data.access_token
            }
        }, (result) => {
            console.log('statusCode: ' + result.statusCode)
            console.log('headers:', result.headers)
            result.on('data', (d) => {
                // process.stdout.write(d);
                reslove(JSON.parse(d.toString()))
            });

        })
        request.on('error', (e) => {
            console.error(e);
        });
        request.end()
    })
}

function getWeChatAccessToken() {
    return new Promise((reslove, reject) => {
        let file = {
            access_token: '',
            expires_in: 0
        }
        //读取凭证
        try {
            const data = fs.readFileSync('./access_token.txt')
            file = JSON.parse(data)
            // process.stdout.write(file)

        } catch (error) {
            console.log(error)
        }

        if (file.expires_in < Date.now()) {
            console.log('凭证过期，重新获取')
            //获取凭证
            const request = https.request(uri, result => {
                console.log('statusCode: ' + result.statusCode)
                console.log('headers:', result.headers)
                result.on('data', (d) => {
                    // process.stdout.write(d);
                    const data = JSON.parse(d.toString())

                    data.expires_in = Date.now() + (data.expires_in * 1000)

                    //保存凭证
                    fs.writeFileSync('./access_token.txt', JSON.stringify(data))
                    reslove(data)
                });
            })
            request.on('error', (e) => {
                console.error(e);
            });
            request.end()

        } else {
            console.log('凭证未过期，读取凭证')
            reslove(file)
        }
    })
}

module.exports = {
    getWeChatAccessToken,
    getWeChatUrlScheme
}